package com.maiji.cloud.controller.login;

import com.google.common.collect.Maps;
import com.maiji.cloud.controller.BaseController;
import com.maiji.cloud.entities.login.FunctionMemu;
import com.maiji.cloud.entities.login.Label;
import com.maiji.cloud.entities.login.MaijiArticle;
import com.maiji.cloud.request.BaseDataReqDto;
import com.maiji.cloud.request.BaseInputDto;
import com.maiji.cloud.request.SaveURBelongIdReqDto;
import com.maiji.cloud.request.login.AppVersionInfoReqData;
import com.maiji.cloud.request.login.ArticleCommentReqData;
import com.maiji.cloud.request.login.CheckCodeReqData;
import com.maiji.cloud.request.login.SendCodeReqDto;
import com.maiji.cloud.response.BaseDataResDto;
import com.maiji.cloud.response.BaseMetaResDto;
import com.maiji.cloud.response.BaseResDto;
import com.maiji.cloud.response.login.*;
import com.maiji.cloud.response.Status;
import com.maiji.cloud.response.shopingmall.BannerImgsResData;
import com.maiji.cloud.response.shopingmall.GetShoppingBannerImgsResDto;
import com.maiji.cloud.utils.MaijiOSS;
import com.maiji.cloud.utils.UUID_MD5;
import com.maiji.cloud.utils.Unlogin;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/common/")
@Api(tags = {"公用模块"})
public class CommonController extends BaseController {

    @Unlogin
	@PostMapping("uploadAppVersionInfo")
	@ApiOperation(value = "上传app版本")
	public BaseDataResDto uploadAppVersionInfo(@RequestBody MultipartFile uploadFile,
                                               @RequestHeader(name = "mapHeader" ,required = false) Map<String,Object> mapHeader ) {
        String bucketName = "maiji-static-images";
    	String fileName = uploadFile.getOriginalFilename();
        String fileExtName = fileName.substring(fileName.lastIndexOf(".")+1);
        String objName = "麦吉减肥法"+mapHeader.get("versionname") + "." + fileExtName;
        
        try {
			if (! MaijiOSS.aliyunOSSUpload2(bucketName, objName, uploadFile.getInputStream()))
			    return new BaseDataResDto(Status.ERROR.setMessage("保存文件至阿里云OSS失败"));
		} catch (IOException e) {
			e.printStackTrace();
			 return new BaseDataResDto(Status.ERROR);
		}
        
        String url = "https://" + bucketName + ".oss-cn-beijing.aliyuncs.com/" + objName;
       
        BaseDataReqDto<AppVersionInfoReqData> param = new BaseDataReqDto<AppVersionInfoReqData>();
        AppVersionInfoReqData data = new AppVersionInfoReqData();
        data.setType(Integer.parseInt((String)mapHeader.get("type")));
        data.setUrl(url);
        data.setDescription(mapHeader.get("description")+"");
        data.setVersionCode(mapHeader.get("versioncode")+"");
        data.setVersionName(mapHeader.get("versionname")+"");
        param.setData(data);
        if(mapHeader.get("isforce") == null) data.setIsForce(0);else data.setIsForce(Integer.parseInt((String)mapHeader.get("isforce")));
        param.setData(data);
		return postForObjectWithToken(mapHeader.get("maijitoken")+"", REST_URL_APPLOGIN + "/common/uploadAppVersionInfo", param, BaseDataResDto.class);
	
	}

	@Unlogin
	@PostMapping("getAppVersionInfo")
	@ApiOperation(value = "获取App版本数据")
    public BaseDataResDto<AppVersionInfoResData> getAppVersionInfo(@RequestBody BaseDataReqDto<Integer> param ,@RequestHeader(value="maijiToken",required =false) String token) {
		
		return postForObjectWithToken(token, REST_URL_APPLOGIN + "/common/getAppVersionInfo", param, BaseDataResDto.class);
	}

    /**
     *  上传视频（批量）
     * @param uploadFiles
     * @param token
     * @return
     */
    @ApiOperation(value = "上传视频（批量）")
    @PostMapping("uploadVideos")
    public BaseDataResDto<List<UploadImageResData>> uploadVideos (@RequestBody MultipartFile[] uploadFiles, @RequestHeader("maijiToken") String token) {
        try {
            Calendar calendar = Calendar.getInstance();
            String bucketName = "maiji-user-videos-" + calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.MONTH);
            return postForObjectWithMultiparts(token, bucketName, uploadFiles, REST_URL_APPLOGIN + "/common/uploadVideos", BaseDataResDto.class);
        } catch (IOException e) {
            e.printStackTrace();
            return new BaseDataResDto<>(Status.ERROR);
        }
    }

    /**
     *  上传图片（批量）
     * @param uploadFiles
     * @param token
     * @return
     */
    @ApiOperation(value = "上传图片（批量）")
    @PostMapping("uploadImage")
    public BaseDataResDto<List<UploadImageResData>> uploadImage (@RequestBody MultipartFile[] uploadFiles, @RequestHeader("maijiToken") String token) {
        try {
            Map<String, Map<String, Object>> map = Maps.newHashMap();
            //设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.add("maijiToken", token);
            //遍历文件数组
            for(MultipartFile uploadFile: uploadFiles) {
                BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream());
                if(bufferedImage == null) continue;
                String fileName = uploadFile.getOriginalFilename();
                String fileExtName = fileName.substring(fileName.lastIndexOf(".")+1);
                String objName = UUID_MD5.getUUID() + "." + fileExtName;
                Calendar calendar = Calendar.getInstance();
                String bucketName = "maiji-user-images-" + calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.MONTH);
                if (! MaijiOSS.aliyunOSSUpload2(bucketName, objName, uploadFile.getInputStream())) return new BaseDataResDto(Status.ERROR);
                Map<String, Object> mapObj = Maps.newHashMap();
                mapObj.put("url", "https://" + bucketName + ".oss-cn-beijing.aliyuncs.com/" + objName);
                mapObj.put("bucketName", bucketName);
                mapObj.put("width", bufferedImage.getWidth());
                mapObj.put("height", bufferedImage.getHeight());
                map.put(objName, mapObj);
            }
            //用HttpEntity封装整个请求报文
            HttpEntity<Map<String, Map<String, Object>>> httpEntity = new HttpEntity<>(map, headers);
            return restTemplate.postForObject(REST_URL_APPLOGIN + "/common/uploadImage", httpEntity, BaseDataResDto.class);
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseDataResDto(Status.ERROR);
        }
    }

    /**
     * 上传单个视频
     * @param videoFile
     * @param token
     * @return
     @PostMapping("uploadVideo")
     @ApiOperation(value = "上传单个视频")
     public BaseDataResDto<UploadImageResData> uploadVideo (@RequestBody MultipartFile videoFile, @RequestHeader("maijiToken") String token){
     List<File> files = Lists.newArrayList();
     try {
     MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
     //设置请求头
     HttpHeaders headers = new HttpHeaders();
     MediaType type = MediaType.parseMediaType("multipart/form-data");
     headers.setContentType(type);
     headers.add("maijiToken", token);
     String fileName = videoFile.getOriginalFilename();
     File localFile = new File(fileName);
     FileUtils.copyInputStreamToFile(videoFile.getInputStream(), localFile);
     files.add(localFile);
     //多个MultipartFile同时添加进 MultiValueMap  key为file
     //MultiValueMap可以让一个key对应多个value
     param.add("videoFile", new FileSystemResource(localFile));
     //用HttpEntity封装整个请求报文
     HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers);
     return restTemplate.postForObject(REST_URL_APPLOGIN + "/common/uploadVideo", httpEntity, BaseDataResDto.class);
     } catch (Exception e) {
     e.printStackTrace();
     return new BaseDataResDto(Status.ERROR);
     } finally {  //删除临时文件
     for (File file: files)
     if (file.exists()) file.delete();
     }
     }
     */

    /**
     * 设置资源列表的归属ID
     * @param inputDto
     * @return
     */
    @ApiOperation(value = "设置资源列表的归属ID")
    @PostMapping("saveURBelongId")
    public BaseDataResDto<Boolean> saveBelongId(@RequestBody BaseInputDto<ArrayList<SaveURBelongIdReqDto>> inputDto){

        return restTemplate.postForObject(REST_URL_APPLOGIN + "/common/saveURBelongId",inputDto, BaseDataResDto.class);
    }

    /**
     *  首页获取功能菜单
     * @param maijiToken
     * @return
     */
    @PostMapping("getFunctionMenus")
	@ApiOperation(value = "获取功能菜单")
	public FunctionMenuResDto getFunctionMenus(@RequestHeader("maijiToken")String maijiToken){
		HttpHeaders headers = new HttpHeaders();
		headers.add("maijiToken", maijiToken);
		HttpEntity<String> httpEntity = new HttpEntity<>(headers);
		return restTemplate.postForObject(REST_URL_APPLOGIN + "/common/getFunctionMenus", httpEntity, FunctionMenuResDto.class);
	}
    
    /**
     *  获取小程序首页功能菜单列表
     * @param maijiToken
     * @return
     */
    @Unlogin
    @PostMapping("getAppletFunctionMenus")
    @ApiOperation(value = "获取小程序功能菜单")
    public FunctionMenuResDto getAppletFunctionMenus(@RequestHeader(value="maijiToken",required =false)String maijiToken){
    	HttpHeaders headers = new HttpHeaders();
		headers.add("maijiToken", maijiToken);
		HttpEntity<String> httpEntity = new HttpEntity<>(headers);
		return restTemplate.postForObject(REST_URL_APPLOGIN + "/common/getAppletFunctionMenus", httpEntity, FunctionMenuResDto.class);
    }

    /**
     *  发送验证码
     * @param sendCodeReqDto
     * @return
     */
    @Unlogin
    @ApiOperation(value = "发送验证码")
    @PostMapping("sendCode")
    public BaseResDto sendCode (@RequestBody SendCodeReqDto sendCodeReqDto) {
        return restTemplate.postForObject(REST_URL_APPLOGIN + "/common/sendCode", sendCodeReqDto, BaseResDto.class);
    }

    @Unlogin
    @PostMapping("tokenInvalid")
    public BaseResDto tokenInvalid () {
        return new BaseResDto(Status.TOKENINVALID);
    }

    /**
     * 获取商品列表轮播图
     * @return
     */
    @Unlogin
    @PostMapping("getShoppingBannerImgs")
    @ApiOperation(value = "获取商品列表轮播图")
    public GetShoppingBannerImgsResDto getShoppingBannerImgs(){
    	return restTemplate.postForObject(REST_URL_APPLOGIN + "/common/getShoppingBannerImgs", null, GetShoppingBannerImgsResDto.class);
    }

    /**
     * 获取商城展示图
     * @return
     */
    @Unlogin
    @PostMapping("findShoppingImg")
    @ApiOperation(value = "获取商城展示图")
    public BaseDataResDto<FunctionMemu> findShoppingImg (){
    	return restTemplate.postForObject(REST_URL_APPLOGIN + "/common/findShoppingImg", null, BaseDataResDto.class);
    }

    /**
     * 获取APP个人中心展示图
     * @return
     */
    @Unlogin
    @PostMapping("findAppIndexImg")
    @ApiOperation(value = "获取APP个人中心展示图")
    public BaseDataResDto<FunctionMemu> findAppIndexImg (){
    	return restTemplate.postForObject(REST_URL_APPLOGIN + "/common/findAppIndexImg", null, BaseDataResDto.class);
    }

    /**
     * 获取微信小程序个人中心展示图
     * @return
     */
    @Unlogin
    @PostMapping("findWxIndexImg")
    @ApiOperation(value = "获取微信小程序个人中心展示图")
    public BaseDataResDto<FunctionMemu> findWxIndexImg (){
    	return restTemplate.postForObject(REST_URL_APPLOGIN + "/common/findWxIndexImg", null, BaseDataResDto.class);
    }

    /**
     * 获得商品评论的标签
     * @return
     */
    @PostMapping("getLabels")
    public BaseDataResDto<List<String>> getLabels(@RequestHeader("maijiToken")String maijiToken){
    	return restTemplate.postForObject(REST_URL_APPLOGIN + "/common/getLabels", null, BaseDataResDto.class);
    }

    /**
     *  获取麦吉简介列表标签[]
     * @return
     */
    @Unlogin
    @ApiOperation(value = "获取麦吉简介列表标签[]")
    @PostMapping("findAllMaijiArticleListLabels")
    public BaseDataResDto<List<LabelResData>> findAllMaijiArticleListLabels () {
        return restTemplate.postForObject(REST_URL_APPLOGIN + "/common/findAllLabelsBySource",
                new BaseDataReqDto<Label>().setData(new Label().setSource("麦吉简介").setListShow(3)), BaseDataResDto.class);
    }

    /**
     *  根据标签ID获取麦吉简介文章列表[]
     * @return
     */
    @ApiOperation(value = "根据标签ID获取麦吉简介文章列表[]")
    @PostMapping("findAllMaijiArticleByLabelId")
    @Unlogin
    public BaseDataResDto<List<MaijiArticleResData>> findAllMaijiArticleByLabelId (@RequestBody BaseDataReqDto<String> baseDataReqDto) {
        return restTemplate.postForObject(REST_URL_APPLOGIN + "/article/findAllMaijiArticleByLabelId", baseDataReqDto, BaseDataResDto.class);
    }

    /**
     * 获得积分商城轮播图
     * @return
     */
    @Unlogin
    @PostMapping("getIntegralShoppingBanner")
    @ApiOperation(value = "获得积分商城轮播图")
    public BaseDataResDto<List<BannerImgsResData>>  getIntegralShoppingBanner(){
    	return restTemplate.postForObject(REST_URL_APPLOGIN + "/common/getIntegralShoppingBanner", null, BaseDataResDto.class);
    }

    /**
     * 获得社区动态轮播图
     * @return
     */
    @Unlogin
    @PostMapping("getCommunityBanner")
    @ApiOperation(value = "获得社区动态轮播图")
    public BaseDataResDto<List<BannerImgsResData>>  getCommunityBanner(@RequestHeader("maijiToken")String maijiToken){
    	return restTemplate.postForObject(REST_URL_APPLOGIN + "/common/getCommunityBanner", null, BaseDataResDto.class);
    }
    /**
	 *    文章点赞
	 * @param param 文章ID
	 * @param token
	 * @return
	 */
    @ApiOperation(value = "文章点赞")
    @PostMapping("articlePraise")
	public BaseResDto articlePraise(@RequestBody BaseDataReqDto<String> param,@RequestHeader("maijiToken") String token){
    	return postForObjectWithToken(token, REST_URL_APPLOGIN + "/article/articlePraise", param,
    			BaseResDto.class);
	}

    /**
	 * 根据文章ID获取点赞用户列表
	 * @param param
	 * @return
	 */
    @ApiOperation(value = "根据文章ID获取点赞用户列表")
    @PostMapping("getArticlePraiseList")
    @Unlogin
	public BaseMetaResDto<List<UserInfoResData>> getArticlePraiseList(@RequestBody BaseDataReqDto<String> param){
		return postForObjectWithToken(null, REST_URL_APPLOGIN + "/article/getArticlePraiseList", param,
				BaseMetaResDto.class);
	}

    /**
	 *    文章转发
	 * @param param 文章ID
	 * @param token
	 * @return
	 */
	@PostMapping("articleTranspond")
	@ApiOperation(value = "文章转发")
	public BaseResDto articleTranspond(@RequestBody BaseDataReqDto<String> param,@RequestHeader("maijiToken") String token){
		return postForObjectWithToken(token, REST_URL_APPLOGIN + "/article/articleTranspond", param,
    			BaseResDto.class);
	}

	/**
	 * 文章评论/评论回复
	 * @param param
	 * @param token
	 * @return
	 */
	@PostMapping("articleComment")
	@ApiOperation(value = "文章评论/评论回复")
	public BaseResDto articleComment(@RequestBody BaseDataReqDto<ArticleCommentReqData> param,@RequestHeader("maijiToken") String token){
		return postForObjectWithToken(token, REST_URL_APPLOGIN + "/article/articleComment", param,
    			BaseResDto.class);
	}

	/**
	 * 获得评论信息(分页)
	 * @param param
	 * @return
	 */
	@PostMapping("getArticleCommentList")
	@ApiOperation(value = "获得评论信息(分页)")
	@Unlogin
	public BaseMetaResDto<List<ArticleCommentListResData>> getArticleCommentList(@RequestBody BaseDataReqDto<String> param,
                                                                                 @RequestHeader(name = "maijiToken", required = false) String token){
		return postForObjectWithToken(token,REST_URL_APPLOGIN + "/article/findAllArticleComments", param, BaseMetaResDto.class);
	}

	@Unlogin
	@PostMapping("getArticleCommentReply")
	@ApiOperation(value = "根据评论ID获得评论回复列表（分页）")
	public BaseMetaResDto<List<ArticleCommentListResData>> getArticleCommentReply(@RequestBody BaseDataReqDto<String> param,@RequestHeader(value="maijiToken",required =false)  String token){
		return postForObjectWithToken(token, REST_URL_APPLOGIN + "/article/getArticleCommentReply", param,
				BaseMetaResDto.class);
	}

	/**
	 * 文章取消点赞
	 * @param param
	 * @param token
	 * @return
	 */
	@PostMapping("cancelArticlePraise")
	@ApiOperation(value = "文章取消点赞")
	public BaseResDto cancelArticlePraise(@RequestBody BaseDataReqDto<String> param,@RequestHeader("maijiToken") String token) {
		return postForObjectWithToken(token, REST_URL_APPLOGIN + "/article/cancelArticlePraise", param,
				BaseResDto.class);
	}

	/**
	 * app用户操作删除评论
	 *
	 * @param param
	 * @return
	 */
	@PostMapping("deleteArticleComment")
	@ApiOperation(value = "app用户操作删除评论")
	public BaseResDto deleteArticleComment(@RequestBody BaseDataReqDto<String> param, @RequestHeader("maijiToken") String token) {
		return postForObjectWithToken(token, REST_URL_APPLOGIN + "/article/deleteArticleComment", param,
				BaseResDto.class);
	}

	 /**
     * 校验验证码
     * @param param
     * @return
     */
    @Unlogin
    @PostMapping("checkCode")
    @ApiOperation(value = "校验短信验证码")
    public BaseDataResDto<Boolean> checkCode(@RequestBody BaseDataReqDto<CheckCodeReqData> param){
    	return restTemplate.postForObject(REST_URL_APPLOGIN + "/common/checkCode", param, BaseDataResDto.class);
    }

    /**
     * 根据文章id判断用户是否点赞/收藏
     * @param param
     * @param token
     * @return
     */
    @PostMapping("isPraiseOrCollect")
    @ApiOperation(value = "根据文章id判断用户是否点赞/收藏")
    public BaseDataResDto<IsPraiseOrCollectResData> isPraiseOrCollect(@RequestBody BaseDataReqDto<String> param, @RequestHeader("maijiToken") String token){
    	return postForObjectWithToken(token, REST_URL_APPLOGIN + "/article/isPraiseOrCollect", param,
    			BaseDataResDto.class);
    }

    /**
	 * 文章收藏
	 *
	 * @param param 文章ID
	 * @param token
	 * @return
	 */
	@PostMapping("articleCollect")
	@ApiOperation(value = "文章收藏")
	public BaseResDto articleCollect(@RequestBody BaseDataReqDto<String> param, @RequestHeader("maijiToken") String token) {
		return postForObjectWithToken(token, REST_URL_APPLOGIN + "/article/articleCollect", param,
				BaseResDto.class);
		}

	/**
	 * 文章取消收藏
	 *
	 * @param param
	 * @param token
	 * @return
	 */
	@PostMapping("cancelArticleCollect")
	@ApiOperation(value = "文章取消收藏")
	public BaseResDto cancelArticleCollect(@RequestBody BaseDataReqDto<String> param, @RequestHeader("maijiToken") String token) {
		return postForObjectWithToken(token, REST_URL_APPLOGIN + "/article/cancelArticleCollect", param,
				BaseResDto.class);

	}

	/**
	 * 文章收藏列表
	 * @param token
	 * @return
	 */
	@PostMapping("articleCollectList")
	@ApiOperation(value = "文章收藏列表")
	public BaseDataResDto<List<MaijiArticle>> articleCollectList(@RequestBody BaseDataReqDto<String> param,@RequestHeader("maijiToken") String token){

		return postForObjectWithToken(token, REST_URL_APPLOGIN + "/article/articleCollectList", param,
				BaseDataResDto.class);
	}

	/**
	 * 获取文章详情
	 * @param baseDataReqDto
	 * @return
	 */
    @Unlogin
	@PostMapping("findMaijiArticleById")
	@ApiOperation(value = "获取文章详情")
	public BaseDataResDto<MaijiArticle> findMaijiArticleById (@RequestBody BaseDataReqDto<String> baseDataReqDto){
		return restTemplate.postForObject(REST_URL_APPLOGIN + "/article/findMaijiArticleById", baseDataReqDto, BaseDataResDto.class);
	}

}
